//
//  NameAuthenticationViewController.m
//  firstpoint
//
//  Created by 泽中 on 2017/7/18.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "NameAuthenticationViewController.h"
#import "ZZYPhotoHelper.h"
#import "BinDingTextView.h"

@interface NameAuthenticationViewController ()<UITextFieldDelegate>
{
    BinDingTextView*nickNameTextField;
    BinDingTextView*idTextField;
    UIImage*img1;
    UIImage*img2;
    NSString*imgType;
    NSString*zhengmianStr;
    NSString*fanmianStr;
}
@end

@implementation NameAuthenticationViewController
-(void)tijiaoHttpRequest
{
  NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"/member/addMemberData.api?access_token="),NSUD_Obj(@"token")];
    [HTTPURL postRequest:url parameters:@{@"realName":nickNameTextField.textField.text,@"cardId":idTextField.textField.text,@"identitypositive":zhengmianStr,@"identityreverse":fanmianStr}success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
    } filure:^(NSURLSessionDataTask *task, id error) {
        
    }];

}
-(void)tijiaoTuPianHttp:(UIImage*)imamg
{      NSString*tokenStr= OBJECT_FOR_KEY(@"token");
    NSString*urlStr=[NSString stringWithFormat:@"common/file/upload.api?access_token=%@",tokenStr];
    
    NSData*data;
    imamg=  [self scaleToSize:imamg size:CGSizeMake(150, 150)];
    if (UIImagePNGRepresentation(imamg)) {
        data=  UIImagePNGRepresentation(imamg);
        
    }else
    {
        data=  UIImageJPEGRepresentation(imamg,1);
        
    }
    NSLog(@"%@",data);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         
                                                         @"text/html",
                                                         
                                                         @"image/jpeg",
                                                         
                                                         @"image/png",
                                                         
                                                         @"application/octet-stream",
                                                         
                                                         @"text/json",
                                                         
                                                         nil];
    
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    
    [manager POST:LINK_BASE_URL(urlStr)  parameters:@{@"userId":userid,@"category":imgType} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //        UIImage *image = [UIImage imageNamed:@"gauge.png"];
        //
        //        NSData *data = UIImagePNGRepresentation(image);
        
        //上传的参数(上传图片，以文件流的格式)
        
        [formData appendPartWithFileData:data
         
                                    name:@"uploadFile"
         
                                fileName:@"gauge.jpg"
         
                                mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功");
        NSLog(@"%@",responseObject);
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        if ([imgType isEqualToString:@"13"]) {
            zhengmianStr=[NSString stringWithFormat:@"%@",dict[@"data"]];
        }else{
           fanmianStr=[NSString stringWithFormat:@"%@",dict[@"data"]];
        }
             
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败%@",error);
        
        
        
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"实名认证";
    
//    [self huoquZhuangTaiHttpRequest];
    self.view.backgroundColor=LRRGBColor(235, 240, 242);
    [self setUI];
    // Do any additional setup after loading the view.
}
-(void)setUI
{
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 74, width_screen, height_screen-138)];
    view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view];
    nickNameTextField=[[BinDingTextView alloc]initWithFrame:CGRectMake(0, 0, width_screen, 46)];
    nickNameTextField.textField.placeholder=@" 输入姓名";
    nickNameTextField.titleLab.text=@"姓名";
    [view addSubview:nickNameTextField];
    
    idTextField=[[BinDingTextView alloc]initWithFrame:CGRectMake(0, 46, width_screen, 46)];
    idTextField.textField.placeholder=@" 输入身份证";
    idTextField.titleLab.text=@"身份证号";
    idTextField.textField.delegate=self;

    [view addSubview:idTextField];
    
    UILabel*zhengmianLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 105, 150, 13)];
    zhengmianLab.text=@"身份证正面照片";
    zhengmianLab.font=[UIFont systemFontOfSize:13];
    [view addSubview:zhengmianLab];
    UIButton*zhengmianButton=[UIButton buttonWithType:UIButtonTypeCustom];
    zhengmianButton.frame=CGRectMake(50, 128, width_screen-100, 130);
    [zhengmianButton setImage:[UIImage imageNamed:@"shddjsc"] forState:0];
    [zhengmianButton addTarget:self action:@selector(zhengmianButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:zhengmianButton];
    
    UILabel*fengeLab=[[UILabel alloc]initWithFrame:CGRectMake(0, 268, width_screen, 1)];
    fengeLab.backgroundColor=LRRGBColor(235, 240, 242);
    [view addSubview:fengeLab];
    UILabel*beimianLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 279, 150, 13)];
    beimianLab.text=@"身份证背面照片";
    beimianLab.font=[UIFont systemFontOfSize:13];
    [view addSubview:beimianLab];
    
    UIButton*beimianButton=[UIButton buttonWithType:UIButtonTypeCustom];
    beimianButton.frame=CGRectMake(50, 302, width_screen-100, 130);
    [beimianButton setImage:[UIImage imageNamed:@"shddjsc"] forState:0];
    [beimianButton addTarget:self action:@selector(fanmianButtonClick:) forControlEvents:UIControlEventTouchUpInside];

    [view addSubview:beimianButton];
    
    
    UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(10, height_screen-60, width_screen-20, 50);
    button.backgroundColor=LRRGBColor(23, 146, 211);
    button.layer.cornerRadius=4;
    [button setTitle:@"确认提交" forState:0];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

        
}
// textField代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // string.length为0，表明没有输入字符，应该是正在删除，应该返回YES。
    if (string.length == 0) {
        return YES;
    }
    // length为当前输入框中的字符长度
    NSUInteger length = textField.text.length + string.length;
    // 如果该页面中还有其他的输入框，则需要做这个判断
    if (textField == idTextField.textField) {
        // str为当前输入框中的字符
        NSString *str = [NSString stringWithFormat:@"%@%@", textField.text, string];
        // 当输入到17位数的时候，通过theLastIsX方法判断最后一位是不是X
        if (length == 17 && [self theLastIsX:str]) {
            // 如果是17位，并通过前17位计算出18位为X，自动补全，并返回NO，禁止编辑。
            textField.text = [NSString stringWithFormat:@"%@%@X", textField.text, string];
            return NO;
        }
        // 如果是其他情况则直接返回小于等于18（最多输入18位）
        return length <= 18;
    }
    return YES;
}
// 判断最后一个是不是X
- (BOOL)theLastIsX:(NSString *)IDNumber {
    NSMutableArray *IDArray = [NSMutableArray array];
    for (int i = 0; i < 17; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [IDNumber substringWithRange:range];
        [IDArray addObject:subString];
    }
    NSArray *coefficientArray = [NSArray arrayWithObjects:@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2", nil, nil];
    int sum = 0;
    for (int i = 0; i < 17; i++) {
        int coefficient = [coefficientArray[i] intValue];
        int ID = [IDArray[i] intValue];
        sum += coefficient * ID;
    }
    if (sum % 11 == 2) return YES;
    else return NO;
}


-(void)buttonClick
{
    [self tijiaoHttpRequest];
}
-(void)zhengmianButtonClick:(UIButton*)btn
{  imgType=@"13";
    [[ZZYPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
        [btn setImage:data forState:0];
        img1=data;
        [self tijiaoTuPianHttp:img1];

    }];

    }
-(void)fanmianButtonClick:(UIButton*)btn
{imgType=@"14";
    [[ZZYPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
        [btn setImage:data forState:0];
        img2=data;
        [self tijiaoTuPianHttp:img2];

    }];
}
-(UIImage *)scaleToSize:(UIImage *)image size:(CGSize)size
{
    //创建一个bitmap的context
    //并把他设置成当前的context
    UIGraphicsBeginImageContext(size);
    //绘制图片的大小
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    //从当前context中创建一个改变大小后的图片
    UIImage *endImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return endImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
